import re

from django.contrib.auth import authenticate
from django.contrib.auth.base_user import AbstractBaseUser
from django_redis import get_redis_connection

from ninja import Field
from ninja.schema import Schema
from ninja_extra import status
from ninja_extra.exceptions import APIException
from pydantic import model_validator

from users.models import User


class QQUserInSchema(Schema):
    """QQopenid绑定用户"""
    mobile: str = Field(..., description="手机号")
    password: str = Field(..., description="密码")
    sms_code: int = Field(..., description="验证码")
    access_token: str = Field(..., description='openid')

    @model_validator(mode='after')
    def check_schema(cls, values):
        if not re.match(r'1[3-9]\d{9}', values.mobile):
            raise APIException({'msg': '请输入正确的手机格式'})

        if User.objects.filter(mobile=values.mobile).exists():
            user = User.objects.get(mobile=values.mobile)
            if user.check_password(values.password) is False:
                raise APIException({'msg': '密码错误，请重新输入'})
            # else:
            #     values.mobile = user

        # if len(values.password) < 6 or len(values.password) > 16:
        #     raise ValueError('密码长度最小6位，最大16位')

        # 校验验证码
        redis_conn = get_redis_connection('verify_code')
        redis_sms_code = redis_conn.get(f'sms_{values.mobile}')
        # redis中存储的是byte类型(b'519210')，所以需要decode(),注意 if 判断的顺序
        # values.sms_code, redis_sms_code.decode()     <class 'int'> <class 'str'>
        if redis_sms_code is None or str(values.sms_code) != redis_sms_code.decode():
            raise APIException({'msg': '验证码错误，请重新输入'})

        return values
